bl_info = {
    "name": "wf_red_last",
    "blender": (3, 6, 0),
    "category": "Object",
    "author": "Wang",
    "version": (1, 0),
    "description": "Create red spheres based on a sum calculation",
    "location": "View3D > Add > Mesh",
    "warning": "",
    "wiki_url": "",
    "tracker_url": "",
}

import bpy

class OBJECT_OT_create_red_spheres(bpy.types.Operator):
    bl_idname = "object.create_red_spheres"
    bl_label = "Create Red Spheres"
    bl_options = {'REGISTER', 'UNDO'}
    
    def execute(self, context):
        def set_object_color_to_red(obj):
            try:
                # 创建材质
                mat = bpy.data.materials.new(name=f"Material_{obj.name}")
                mat.use_nodes = True
                
                # 获取材质的节点树
                nodes = mat.node_tree.nodes
                bsdf = nodes.get("Principled BSDF")
                
                if bsdf:
                    # 设置红色
                    red_color = (1, 0, 0, 1)  # 固定红色
                    bsdf.inputs['Base Color'].default_value = red_color
                
                # 将材质分配给物体
                if obj.data.materials:
                    obj.data.materials[0] = mat
                else:
                    obj.data.materials.append(mat)
                
                return True
            except Exception as e:
                self.report({'ERROR'}, f"Failed to set color for {obj.name}: {e}")
                return False
        
        def sum_numbers():
            total = 0
            for i in range(1, 4):
                total += i
                print(f'Current sum at i={i} is {total}')  # 您可以在这里设置断点
            return total
        
        result = sum_numbers()
        self.report({'INFO'}, f'Total sum is {result}')  # 打印累加结果总和

        bpy.ops.object.select_all(action='SELECT')  # 选择所有物体
        bpy.ops.object.delete(use_global=False)  # 删除所有物体

        for i in range(result):
            # 创建球体
            bpy.ops.mesh.primitive_uv_sphere_add(radius=1, enter_editmode=False, align='WORLD', location=(i*3, 0, 0), scale=(1, 1, 1))
            sphere = bpy.context.object
            
            # 设置球体颜色为红色
            if set_object_color_to_red(sphere):
                self.report({'INFO'}, f"Successfully set color for {sphere.name}")
            else:
                self.report({'ERROR'}, f"Failed to set color for {sphere.name}")

        # 设置视图模式为Material Preview
        for area in context.screen.areas:
            if area.type == 'VIEW_3D':
                for space in area.spaces:
                    if space.type == 'VIEW_3D':
                        space.shading.type = 'MATERIAL'
        
        return {'FINISHED'}

# 菜单项
def menu_func(self, context):
    self.layout.operator(OBJECT_OT_create_red_spheres.bl_idname)

# 注册和反注册功能
def register():
    bpy.utils.register_class(OBJECT_OT_create_red_spheres)
    bpy.types.VIEW3D_MT_mesh_add.append(menu_func)

def unregister():
    bpy.utils.unregister_class(OBJECT_OT_create_red_spheres)
    bpy.types.VIEW3D_MT_mesh_add.remove(menu_func)

if __name__ == "__main__":
    register()
